package com.team9.fitness.controller;

import com.team9.fitness.entity.CommunityPost;
import com.team9.fitness.service.CommunityPostService;
import com.team9.fitness.service.ZRDDSDataExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社区动态管理控制器
 * 
 * 提供健身社区功能：
 * - 发布动态：用户分享健身心得、成果
 * - 查看动态：浏览所有用户的健身动态（包含点赞、喜欢、评论统计）
 * - 用户动态：查看特定用户的动态历史
 * - 动态详情：查看单条动态的详细信息
 * - 删除动态：用户删除自己的动态
 * 
 * 支持功能：
 * - 动态内容管理
 * - 用户权限控制
 * - 动态列表分页
 * - 点赞、喜欢、评论统计
 * - 用户交互状态查询
 */
@RestController
@RequestMapping("/api/community-posts")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
@Slf4j
public class CommunityPostController {

    @Autowired
    private CommunityPostService communityPostService;

    @Autowired
    private ZRDDSDataExchangeService zrddsDataExchangeService;

    /**
     * 创建帖子
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createPost(@RequestBody CommunityPost post) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 直接执行业务逻辑
            CommunityPost createdPost = communityPostService.createPost(post);
            response.put("success", true);
            response.put("message", "帖子创建成功");
            response.put("data", createdPost);

            // 业务逻辑成功，发布数据到ZRDDS作为记录
            try {
                Map<String, Object> additionalData = new HashMap<>();
                additionalData.put("title", post.getTitle());
                additionalData.put("content", post.getContent());
                additionalData.put("createTime", java.time.LocalDateTime.now().toString());

                zrddsDataExchangeService.publishCommunityActivity("CREATE_POST",
                        post.getUserId(), post.getId(), additionalData);
            } catch (Exception e) {
                log.warn("发布社区活动数据到ZRDDS失败", e);
                // 不影响业务逻辑
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建帖子失败", e);
            response.put("success", false);
            response.put("message", "创建失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取所有帖子（包含统计信息）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllPosts(@RequestParam(required = false) Long currentUserId) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 如果未提供currentUserId，使用0表示未登录用户
            Long userId = currentUserId != null ? currentUserId : 0L;
            List<CommunityPost> posts = communityPostService.getAllPosts(userId);
            response.put("success", true);
            response.put("data", posts);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取帖子列表失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据用户ID获取帖子（包含统计信息）
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getPostsByUserId(@PathVariable Long userId,
            @RequestParam(required = false) Long currentUserId) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 如果未提供currentUserId，使用0表示未登录用户
            Long currentUser = currentUserId != null ? currentUserId : 0L;
            List<CommunityPost> posts = communityPostService.getPostsByUserId(userId, currentUser);
            response.put("success", true);
            response.put("data", posts);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户帖子失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据ID获取帖子（包含统计信息）
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getPostById(@PathVariable Long id,
            @RequestParam(required = false) Long currentUserId) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 如果未提供currentUserId，使用0表示未登录用户
            Long currentUser = currentUserId != null ? currentUserId : 0L;
            var post = communityPostService.getPostById(id, currentUser);
            if (post.isPresent()) {
                response.put("success", true);
                response.put("data", post.get());
            } else {
                response.put("success", false);
                response.put("message", "帖子不存在");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取帖子失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 更新帖子
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updatePost(@PathVariable Long id, @RequestBody CommunityPost post) {
        Map<String, Object> response = new HashMap<>();

        try {
            post.setId(id);
            CommunityPost updatedPost = communityPostService.updatePost(post);
            response.put("success", true);
            response.put("message", "帖子更新成功");
            response.put("data", updatedPost);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新帖子失败", e);
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 删除帖子
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deletePost(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();

        try {
            communityPostService.deletePost(id);
            response.put("success", true);
            response.put("message", "帖子删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除帖子失败", e);
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}
